package org.example.interceptor;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import org.example.common.SerializationInterface;
import org.example.entity.Calculatepojo;
import org.example.service.RpcService;
import org.example.entity.CalculateProto;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * rpc调用的动态代理类
 */
public class RpcInterceptor implements InvocationHandler {

    private Object target;
    private RpcService myClient = new RpcService();

    public RpcInterceptor(Object target) {
        this.target = target;
    }

    public static Object createProxy(Object target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new RpcInterceptor(target));
        return enhancer.create();
    }

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        //序列化
        System.out.println("------动态代理开始");
        SerializationInterface cal = (SerializationInterface) objects[0];
        byte[] requestBytes = cal.toSerialization(cal);
        System.out.println("客户端序列化后字节数组：" + Arrays.toString(requestBytes));
        myClient.startConnection("127.0.0.1",9999);
        byte[] responseBytes = myClient.sendMessage(requestBytes);
        System.out.println("收到服务端返回的字节数组：" + Arrays.toString(responseBytes));
        //反序列化
        System.out.println("------反序列化");
        o = cal.reverseSerialization(responseBytes);
        System.out.println("------动态代理结束");
        method.invoke(target, objects);
        return o;
    }
}
